<script setup lang="ts">
import MainLayout from '@/components/layouts/MainLayout.vue'
import LoginForm from '@/components/LoginForm.vue'
import { useAuth } from '@/composables/auth'
import { useToastStore } from '@/stores/toast'
import { ref } from 'vue'

const { login, register } = useAuth()
const toastStore = useToastStore()
const error = ref('')
const loading = ref(false)

const handleLogin = async (credentials: { username: string; password: string }) => {
  error.value = ''
  loading.value = true
  try {
    const response = await login(credentials.username, credentials.password)
    if (response.success) {
      toastStore.addToast('登录成功！', 'success')
    } else {
      toastStore.addToast('登录失败，请检查用户名和密码', 'error')
    }
  } catch (e: any) {
    error.value = e.message
    toastStore.addToast('登录失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}

const handleRegister = async (credentials: { username: string; password: string }) => {
  error.value = ''
  loading.value = true
  try {
    await register(credentials.username, credentials.password)
    toastStore.addToast('注册成功！', 'success')
  } catch (e: any) {
    error.value = e.message
    toastStore.addToast('注册失败，请重试', 'error')
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <MainLayout>
    <div class="login-view">
      <Transition name="fade">
        <div v-if="error" class="nes-container is-rounded is-error message">
          <i class="nes-icon close is-small"></i>
          {{ error }}
          <button 
            class="close-btn nes-btn is-error"
            @click="error = ''"
          >
            ×
          </button>
        </div>
      </Transition>
      <LoginForm 
        @login="handleLogin"
        @register="handleRegister"
      />
      <LoadingSpinner v-if="loading" />
    </div>
  </MainLayout>
</template>

<style scoped>
.login-view {
  max-width: 600px; /* 限制最大宽度 */
  margin: 0 auto; /* 居中对齐 */
  padding: 1rem;
  height: 100%; /* 使用容器高度 */
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
  align-items: center; /* 水平居中 */
}

.message {
  margin-bottom: 1rem;
  padding: 1rem;
  text-align: center;
  font-size: 0.8rem;
  display: flex;
  align-items: center;
  gap: 1rem;
}

.message i {
  flex-shrink: 0;
}

.close-btn {
  position: absolute;
  right: 0.5rem;
  top: 50%;
  transform: translateY(-50%);
  min-width: auto;
  width: 24px;
  height: 24px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
}

/* 添加错误消息动画 */
.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

/* 确保在大屏幕下不出现滚动条 */
@media (min-width: 1920px) {
  body {
    overflow: hidden; /* 禁用滚动条 */
  }
}
</style> 